import hashlib
import json
import os
import random
import string

import openai as openai
import requests

from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from myapp.models import UserInfo

from myapp.genUserSig import TLSSigAPIv2
from myproject import settings


class T_IM(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        action = kwargs.pop('action', None)
        if action == 'Create_account':
            return self.Create_account(request, *args, **kwargs)
        elif action == 'imuserinfo':
            return self.imuserinfo(request, *args, **kwargs)
        elif action == 'upload_image':
            return self.upload_image(request, *args, **kwargs)
        elif action == 'ai':
            return self.ai(request, *args, **kwargs)
        else:
            return super().dispatch(request, *args, **kwargs)

    @method_decorator(csrf_exempt)
    def Create_account(self, request, *args, **kwargs):
        data = json.loads(request.body)
        username = data.get('username')
        if UserInfo.objects.filter(username=username).exists():
            return JsonResponse({}, safe=False, status=200)
        else:
            api = TLSSigAPIv2(1400828049, '60c58ae3b7eaa37dc2b66075f13a70645a5b01861e1c258f4291a0e4896b8d62')
            sig = api.genUserSig("administrator")
            url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import"
            payload = {
               "UserID":username,
               "Nick":username,
               "FaceUrl":"http://10.12.28.129/image/user.jpg"
            }
            headers = {
                'Content-Type': 'application/json',
            }
            params = {
                'usersig': sig,
                'identifier': 'administrator',
                'sdkappid': '1400828049',
                'random': '99999999',
                'contenttype': 'json',
            }
            response = requests.post(url, headers=headers, params=params, json=payload)
            if response.status_code == 200:
                result = response.json()
                # print(result)
                return JsonResponse({}, safe=False, status=200)
            else:
                print("请求失败:")
                # print(response.status_code)
                return JsonResponse(response.status_code)

    @method_decorator(csrf_exempt)
    def imuserinfo(self, request, *args, **kwargs):
        data = json.loads(request.body)
        username = data.get('cardid')
        sex = data.get('sex')
        imageUrl = data.get('imageUrl')
        if sex == '男':
            sex = 'Gender_Type_Male'
        elif sex == '女':
            sex = 'Gender_Type_Female'
        else:
            sex = 'Gender_Type_Unknown'
        api = TLSSigAPIv2(1400828049, '60c58ae3b7eaa37dc2b66075f13a70645a5b01861e1c258f4291a0e4896b8d62')
        sig = api.genUserSig("administrator")
        url = "https://console.tim.qq.com/v4/profile/portrait_set"
        payload = {
            "From_Account":username,
            "ProfileItem":
            [
                {
                    "Tag":"Tag_Profile_IM_Gender",
                    "Value":sex
                },
                {
                    "Tag": "Tag_Profile_IM_Image",
                    "Value": imageUrl
                }
            ]
        }
        headers = {
            'Content-Type': 'application/json',
        }
        params = {
            'usersig': sig,
            'identifier': 'administrator',
            'sdkappid': '1400828049',
            'random': '99999999',
            'contenttype': 'json',
        }
        response = requests.post(url, headers=headers, params=params, json=payload)
        if response.status_code == 200:
            result = response.json()
            # print(result)
            return JsonResponse({}, safe=False, status=200)
        else:
            print("请求失败:")
            return JsonResponse(response.status_code)

    @method_decorator(csrf_exempt)
    def upload_image(self,request,*args, **kwargs):
        image_file = request.FILES.get('file')
        username = request.POST.get('username')
        # 将上传的文件保存到MEDIA_ROOT目录下
        if username is None:
            return JsonResponse({'success': True})
        file_path = os.path.join(settings.MEDIA_ROOT, username+'.jpg')
        with open(file_path, 'wb+') as f:
            for chunk in image_file.chunks():
                f.write(chunk)
        # 返回上传成功的响应结果
        url = os.path.join(settings.MEDIA_URL, username+'.jpg').replace('\\', '/')
        return JsonResponse({'success': True, 'data': {'url': url}})

#     @staticmethod
#     @method_decorator(csrf_exempt)
#     def ask_chatgpt(text):
#         """
#         @param text:    对话内容（问题）
#         @return: json   对话结果
#         """
#         prompt = text
#         openai.api_key = "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"
#         # 请求chatgpt的模型智能对话
#         try:
#             completions = openai.Completion.create(
#                 engine="text-davinci-002",
#                 prompt=prompt,
#                 max_tokens=100,
#                 n=1,
#                 stop=None,
#                 temperature=0.5,
#             )
#             message = completions.choices[0].text
#             return message
#         except:
#             return False
#
#     @method_decorator(csrf_exempt)
#     def ai(self, request, *args, **kwargs):
#         data = json.loads(request.body)
#         text = data.get('text')
#         print(self.ask_chatgpt(text))
#         return JsonResponse({'mse':"ok"})
#
#     # 消息内容判断
#     @staticmethod
#     def messaging(reqbody):
#         """
#         @param reqbody:     请求主体
#         @return:
#         """
#         root = reqbody
#         from_account = root.get("From_Account")  # 获取发送方ID
#         if from_account.startswith("@RBT#"):  # 检查发送方ID，不处理机器人发送给机器人的请求，防止无限循环
#             return
#         try:
#             to_account = root.get("To_Account")  # 获取接收方ID
#         except:
#             to_account = ""
#         if from_account.startswith("@RBT#"):
#             # clientSeq_random_serverTime
#             try:
#                 Random = root.get("MsgSeq")  # 获取消息发送时间戳，作为重复消息的判断依据
#             except:
#                 Random = root.get("MsgTime")  # 获取消息发送时间戳，作为重复消息的判断依据
#             msg_body_list = root.get("MsgBody", [])
#             for msg_body in msg_body_list:  # 处理消息内容
#                 msg_type = msg_body.get("MsgType")
#                 if msg_type != "TIMTextElem":
#                     continue
#                 msg_content = msg_body.get("MsgContent")  # 获取消息text
#                 text = msg_content.get("Text")
#
#                 res_content = T_IM.ask_chatgpt(text)  # 在调用chatglm模型之前检测是否调用chatgpt模型
#                 T_IM.return_sign_msg(to_account, from_account, res_content, Random)
#
#     # 调用chatgpt
#     @staticmethod
#     def ask_chatgpt(text):
#         """
#         @param text:    对话内容（问题）
#         @return: json   对话结果
#         """
#         openai.api_type = "azure"
#         openai.api_base = "https://operation.openai.azure.com/"
#         openai.api_version = "2023-05-15"
#         openai.api_key = "d821133d62314ababa457191ba2c5e03"
#
#         response = openai.ChatCompletion.create(
#             # engine="gpt-35-turbo", # engine = "deployment_name".
#             engine="operation",
#             messages=[
#                 {"role": "user", "content": text},
#             ])
#         return response['choices'][0]['message']['content']
#
#     # 单聊消息回复
#     @staticmethod
#     def return_sign_msg(From_Account, To_Account, response, random_):
#         api = TLSSigAPIv2(1400828049, '60c58ae3b7eaa37dc2b66075f13a70645a5b01861e1c258f4291a0e4896b8d62')
#         sig = api.genUserSig("administrator")
#         try:
#             if not From_Account:
#                 return False
#             url = f"https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=1400818670&identifier=administrator&usersig={sig}&random={random.randint(0, 999999)}&contenttype=json"
#             headers = {"Content-Type": "application/json"}
#             body = {
#                 "SyncOtherMachine": 1,
#                 "From_Account": From_Account,
#                 "To_Account": To_Account,
#                 "MsgSeq": OtherCtrl.string_to_number(str(random_)),
#                 "MsgRandom": OtherCtrl.string_to_number(str(random_)),
#                 "MsgBody": [
#                     {
#                         "MsgType": "TIMTextElem",
#                         "MsgContent": {
#                             "Text": response
#                         }
#                     }
#                 ],
#                 # "CloudCustomData": "your cloud custom data"
#             }
#             res = requests.post(url, headers=headers, data=json.dumps(body))
#             if res.status_code != 200:
#                 return False
#             return res.json()
#         except Exception as e:
#             return False
#
# class OtherCtrl:
#
#     # 字符串转32位数字
#     @staticmethod
#     def string_to_number(s):
#         # 使用 SHA-256 哈希算法将字符串转换为字节串
#         b = s.encode('utf-8')
#         h = hashlib.sha256(b)
#         # 将哈希值转换为整数，并取前 8 个字节（即 32 位）
#         n = int.from_bytes(h.digest(), byteorder='big') & 0xffffffff
#         return n
#
#     # 去除字符串内中英文标点和特殊字符
#     @staticmethod
#     def remove_punctuation(s):
#         # 如果字符串的第一个字符或最后一个字符是标点符号或特殊字符串，就去除它
#         while len(s) > 0 and s[0] in string.punctuation:
#             s = s[1:]
#         # 去除尾部标点符号和特殊字符串
#         while len(s) > 0 and s[-1] in string.punctuation:
#             s = s[:-1]
#         # 去除中文标点符号
#         while len(s) > 0 and s[0] in '！@#￥%……&*（）——+~·；：，！？。、“”‘’|》《':
#             s = s[1:]
#         while len(s) > 0 and s[-1] in '！@#￥%……&*（）——+~·；：，！？。、“”‘’|》《':
#             s = s[:-1]
#         return s